//
//  KWNLeftSideViewController.m
//  KWNClient
//
//  Created by 张明磊 on 14-4-15.
//  Copyright (c) 2014年 张明磊. All rights reserved.
//

#import "KWLLeftSideViewController.h"
#import "KWLSetViewController.h"
//#import "KWNShareViewController.h"
#import "KWLHomeViewController.h"
#import "Model_user.h"
#import "RESideMenu.h"
//#import "KWNQuestionListViewController.h"
#import "KWLLoginViewController.h"
#import "KWLEditIntroViewController.h"
#import "KWLFindMMViewController.h"
#import "KWNNetwork.h"
#import "Model_lawyerInfo.h"
#import "UIButton+WebCache.h"
#import "KWLLayerViewController.h"
#import "UMFeedback.h"
#import "MLBlackTransition.h"
#import "KWLMyListViewController.h"
#import "MINavigationController.h"
#import "UIImageView+WebCache.h"
#import "KWLScanCodeViewController.h"
#import "KWLMyGrewupViewController.h"
#import "KWLFeedbackFunctionViewController.h"
@interface KWLLeftSideViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) NSIndexPath *index;
@property (weak, nonatomic) UITableView *tabel_list;
@property (weak, nonatomic) UILabel *label_name;
@property (weak, nonatomic) UIButton *button_login;
@property (strong, nonatomic) Model_lawyerInfo *model_laywer;
@property (strong, nonatomic) NSArray *arr_options;

@end

@implementation KWLLeftSideViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
//        self.view.backgroundColor = RGB(36, 36, 36);
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor redColor];
//    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageFileName:@"shouye_background.png"]];
    
    UIImageView *imageview_leftBack = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    imageview_leftBack.image = [UIImage imageFileName:@"shouye_background.png"];
    imageview_leftBack.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [self.view addSubview:imageview_leftBack];
    _arr_options = @[
                     @{@"image":@"left_shouye.png",@"title":@"首页"},
                     @{@"image":@"left_myAnswer.png",@"title":@"我的回答"},
                     @{@"image":@"left_mygrowup.png",@"title":@"我的成长"},
                     @{@"image":@"left_opinion.png",@"title":@"意见反馈"},
                     @{@"image":@"left_set.png",@"title":@"系统设置"},
                     @{@"image":@"left_saoyisao.png",@"title":@"扫一扫"}
                    ];
    [Model_user sharedInstance].bool_isLoadLawyer = YES;
    [self installViewUI];
    [self regist_notificationLeft];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [self remove_notificationLeft];
}

- (void)viewWillAppear:(BOOL)animated{
    if(!self.navigationController.navigationBarHidden){
        self.navigationController.navigationBarHidden = YES;
        [self.navigationController enabledMLBlackTransition:YES];
        self.navigationController_MI.canDragBack = YES;
    }
    if(_index){
        UITableViewCell *cell = [_tabel_list cellForRowAtIndexPath:_index];
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
    }
    /*NSString *string_name = [[Model_user sharedInstance] getUserName];
    if(string_name){
        _button_login.hidden = YES;
        _label_name.hidden = NO;
        if(_label_name){
            //_label_name.text = [NSString stringWithFormat:@"我的ID:%@",string_name];
        }
        else{
             [_tabel_list reloadData];
        }
    }
    else{
        if(_button_login){
            _button_login.hidden = NO;
        }
        else{
            [_tabel_list reloadData];
        }
        _label_name.hidden = YES;
    }*/
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"LeftPage"];
    
    BOOL reload = [Model_user sharedInstance].bool_isLoadLawyer;
    if(reload){
        [[KWNNetwork sharedInstance] lawyer_getLawyerInformationFinishBlock:^(NSInteger stateCode, NSMutableArray *result) {
            switch (stateCode) {
                case 10000:{
                    Model_lawyerInfo *info = result[0];
                    _model_laywer = info;
    
                    //[[Model_user sharedInstance] setLaywerLevelWith:info.string_level];
                    
                    [Model_user sharedInstance].bool_isLoadLawyer = NO;
                    [_tabel_list reloadData];
                }break;
                default:
                    break;
            }
        }];
    }
}

// AS 快法务 KLW 2014-12-26
- (void)reloadLayerDataForTable;
{
    BOOL reload = [Model_user sharedInstance].bool_isLoadLawyer;
    if(reload){
        [[KWNNetwork sharedInstance] lawyer_getLawyerInformationFinishBlock:^(NSInteger stateCode, NSMutableArray *result) {
            switch (stateCode) {
                case 10000:{
                    Model_lawyerInfo *info = result[0];
                    _model_laywer = info;
                    
                    //[[Model_user sharedInstance] setLaywerLevelWith:info.string_level];
                    
                    [Model_user sharedInstance].bool_isLoadLawyer = NO;
                    [_tabel_list reloadData];
                }break;
                default:
                    break;
            }
        }];
    }
}
// AE 快法务 KLW 2014-12-26

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"LeftPage"];
}

- (void)updateUnReadCount{
    UITableView *tableView_menu = (UITableView *)[self.view viewWithTag:300];
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:1 inSection:0];
    UITableViewCell *cell = [tableView_menu cellForRowAtIndexPath:indexpath];
    UILabel *lab = (UILabel *)[cell viewWithTag:TagOfView];
    
    NSString *unreadcountstr = [[Model_user sharedInstance] getUnReadCount];
    if (unreadcountstr)
    {
        if ([unreadcountstr integerValue] > 0) {
            lab.hidden = NO;
            if([unreadcountstr integerValue]>9)
            {
                lab.text = @"N";
            }
            else
            {
                lab.text = unreadcountstr;
            }
        }
        else
        {
            lab.hidden = YES;
        }
    }
}
#pragma mark - cell点击事件 -
//首页
- (void)clickCell_shouye{
    
    KWLHomeViewController *controller_root = [[KWLHomeViewController alloc] init];
    if (IOS6_VERSION) {
        controller_root.navigationController_MI = (MINavigationController *)[RESideMenu sharedInstance].navigationController;
    }

    [[RESideMenu sharedInstance] setContentViewController:controller_root animated:YES];
}

//我的回答
- (void)clickCell_answer
{
    KWLMyListViewController *controller_my = [[KWLMyListViewController alloc] init];
    if (IOS6_VERSION) {
        controller_my.navigationController_MI = (MINavigationController *)[RESideMenu sharedInstance].navigationController;
    }

    [[RESideMenu sharedInstance] setContentViewController:controller_my animated:YES];
}

//我的成长
- (void)clickCell_mygrowup
{
    
    KWLMyGrewupViewController *controller_grewup = [[KWLMyGrewupViewController alloc] initWithGrewupLeftBtnType:KFWGrewupLeftBtnMenuType andModel:KFWGrewupModelTypeMyLevel];
    if (IOS6_VERSION) {
        controller_grewup.navigationController_MI = (MINavigationController *)[RESideMenu sharedInstance].navigationController;
    }

    [[RESideMenu sharedInstance] setContentViewController:controller_grewup animated:YES];

}

//意见反馈
- (void)clickCell_opinion
{
    NSString *string_token = [[Model_user sharedInstance] getToken];
    if(string_token){
//        self.navigationController.navigationBarHidden = NO;
//        self.navigationController_MI.canDragBack = NO;
//        [self.navigationController enabledMLBlackTransition:NO];
//        [RESideMenu sharedInstance].contentViewController = nil;
        
        KWLFeedbackFunctionViewController *controller_feedback = [[KWLFeedbackFunctionViewController alloc] init];
        if (IOS6_VERSION) {
            controller_feedback.navigationController_MI = (MINavigationController *)[RESideMenu sharedInstance].navigationController;
        }

        [[RESideMenu sharedInstance] setContentViewController:controller_feedback animated:YES];

    }
    else{
        KWLLoginViewController *login = [[KWLLoginViewController alloc] initWithTag:3];
        [self pushViewController:login];
    }

}

//设置
- (void)clickCell_set
{
    KWLSetViewController *controller_set = [[KWLSetViewController alloc] init];
    if (IOS6_VERSION) {
        controller_set.navigationController_MI = (MINavigationController *)[RESideMenu sharedInstance].navigationController;
    }

    [[RESideMenu sharedInstance] setContentViewController:controller_set animated:YES];

}

//扫一扫
- (void)clickCell_saoyisao
{
    KWLScanCodeViewController *scanCode = [[KWLScanCodeViewController alloc] init];
    if (IOS6_VERSION) {
        scanCode.navigationController_MI = (MINavigationController *)[RESideMenu sharedInstance].navigationController;
    }

    [[RESideMenu sharedInstance] setContentViewController:scanCode animated:YES];
}

/**
 *  初始化UI界面
 */
- (void)installViewUI{
    /*NSString *token = [[Model_user sharedInstance] getToken];
    if(token){
        [[KWNNetwork sharedInstance] lawyer_getLawyerInformationFinishBlock:^(NSInteger stateCode, NSMutableArray *result) {
            switch (stateCode) {
                case 10000:{
                    Model_lawyerInfo *info = result[0];
                    _model_laywer = info;
                }break;
                default:
                    break;
            }
        }];
    }*/
    UITableView *tableView_menu = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//    tableView_menu.backgroundColor = RGB(52, 52, 52);
    tableView_menu.delegate = self;
    tableView_menu.dataSource = self;
    tableView_menu.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tableView_menu];
    tableView_menu.separatorColor = RGB(92, 85, 87);
    tableView_menu.scrollEnabled = YES;
    tableView_menu.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    tableView_menu.tag = 300;
    _tabel_list = tableView_menu;
}

#pragma mark - UITableViewDelegate -

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;{
    return 7;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *CellIdentifier = @"Cell_menu";
    NSString *CellOptionsIdentifier = @"Cell_options";

    UITableViewCell *cell = [tableView  dequeueReusableCellWithIdentifier:CellIdentifier];
    UITableViewCell *optionsCell = [tableView  dequeueReusableCellWithIdentifier:CellOptionsIdentifier];
    if (indexPath.row == 0) {
        if (cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor clearColor];
            cell.contentView.backgroundColor = [UIColor clearColor];
            
            UIImageView *imageView_portrait = [[UIImageView alloc] initWithFrame:CGRectMake(40, 30, 70, 70)];
            imageView_portrait.contentMode = UIViewContentModeScaleAspectFill;
            imageView_portrait.layer.masksToBounds = YES;
            imageView_portrait.layer.cornerRadius = 35.0;
            imageView_portrait.layer.borderWidth = 1.0;//边框宽度
            imageView_portrait.layer.borderColor = RGB(228, 228, 228).CGColor;//边框颜色
            imageView_portrait.tag = 10;
            [cell addSubview:imageView_portrait];
            
            UIButton *button_portrait = [UIButton buttonWithType:UIButtonTypeCustom];
            button_portrait.frame = CGRectMake(40, 30, 70, 70);
            button_portrait.backgroundColor = [UIColor clearColor];
            [button_portrait addTarget:self action:@selector(didClickButton_portrait:) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:button_portrait];
            button_portrait.layer.masksToBounds = YES;
            button_portrait.layer.cornerRadius = 35;
            button_portrait.layer.borderWidth = 1.0;//边框宽度
            button_portrait.layer.borderColor = RGB(228, 228, 228).CGColor;//边框颜色
            
            UILabel *label_level = [[UILabel alloc] initWithFrame:CGRectMake(button_portrait.frame.origin.x + button_portrait.frame.size.width + 10, button_portrait.frame.origin.y + 10, 60, 30)];
            label_level.backgroundColor = RGB(69,219,180);
            label_level.textColor = [UIColor whiteColor];
            label_level.textAlignment = NSTextAlignmentCenter;
            label_level.layer.masksToBounds = YES;
            label_level.layer.cornerRadius = 15;
            label_level.font = [UIFont fontWithName:@"Futura-CondensedExtraBold" size:17];
            [cell addSubview:label_level];
            label_level.tag = 11;
            
            UILabel *label_name = [[UILabel alloc] initWithFrame:CGRectMake(button_portrait.frame.origin.x + button_portrait.frame.size.width + 7, button_portrait.frame.origin.y + button_portrait.frame.size.height - 30, 66, 30)];
            label_name.backgroundColor = [UIColor clearColor];
            label_name.textColor = [UIColor whiteColor];
            label_name.textAlignment = NSTextAlignmentCenter;
            label_name.font = [UIFont fontWithName:@"Helvetica-Bold" size:20.0f];
            [cell addSubview:label_name];
            label_name.tag = 12;
        }
        UIImageView *imageView_portrait = (UIImageView *)[cell viewWithTag:10];
        [imageView_portrait sd_setImageWithURL:[NSURL URLWithString:_model_laywer.string_portrait] placeholderImage:[UIImage imageFileName:Default_portrait]];
        UILabel *label_level = (UILabel *)[cell viewWithTag:11];
        label_level.text = [NSString stringWithFormat:@"LV.%@",_model_laywer.string_level];
        UILabel *label_name = (UILabel *)[cell viewWithTag:12];
        label_name.text = _model_laywer.string_realname;
        
        return cell;
    }
    else
    {
        if (optionsCell == nil) {
            optionsCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellOptionsIdentifier];
            optionsCell.selectionStyle = UITableViewCellSelectionStyleNone;
            optionsCell.backgroundColor = [UIColor clearColor];
            optionsCell.contentView.backgroundColor = [UIColor clearColor];
            
            UIImageView *imageview_icon = [[UIImageView alloc] initWithFrame:CGRectMake(60, (52-21)/2, 21, 21)];
            imageview_icon.tag = TagOfView + 1;
            
            UILabel *label_title = [UIUtils creatLabel];
            label_title.font = FontOfHelveticaBold(15);
            label_title.frame = CGRectMake(104, (52 - 21)/2, 100, 21);
            label_title.textColor = [UIColor whiteColor];
            label_title.tag = TagOfView + 2;
            
            [optionsCell addSubview:imageview_icon];
            [optionsCell addSubview:label_title];
        }
        
        UIImageView *imageview_icon_ = (UIImageView *)[optionsCell viewWithTag:TagOfView + 1];
        UILabel *label_title_ = (UILabel *)[optionsCell viewWithTag:TagOfView + 2];
        
        NSDictionary *dic = [_arr_options objectAtIndex:indexPath.row - 1];
        NSString *imageName = [dic objectForKey:@"image"];
        NSString *titleName = [dic objectForKey:@"title"];
        imageview_icon_.image = [UIImage imageFileName:imageName];
        label_title_.text = titleName;

        return optionsCell;
    }
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.backgroundColor = RGB(91, 165, 229);
    cell.contentView.backgroundColor = RGB(91, 165, 229);
//    cell.backgroundColor = [UIColor clearColor];
//    cell.contentView.backgroundColor = [UIColor clearColor];

    return YES;
}

- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.contentView.backgroundColor = [UIColor clearColor];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0){
        return;
    }
    if(_index){
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:_index];
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
    }
    
    [[RESideMenu sharedInstance] hideMenuViewController];

    if (![_index isEqual:indexPath]) {
        _index = indexPath;
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.backgroundColor = RGB(91, 165, 229);
        cell.contentView.backgroundColor = RGB(91, 165, 229);

        if ([[RESideMenu sharedInstance].contentViewController isKindOfClass:[KWLScanCodeViewController class]])
        {
            //timer不放空  无法释放控制器
            KWLScanCodeViewController *control = (KWLScanCodeViewController *)[RESideMenu sharedInstance].contentViewController;
            [control.timer invalidate];
        }
        
        UILabel *label_title = (UILabel *)[cell viewWithTag:TagOfView + 2];
        if ([label_title.text isEqualToString:@"首页"]) {
            [self clickCell_shouye];
        }
        if ([label_title.text isEqualToString:@"我的回答"]) {
            [self clickCell_answer];
        }
        if ([label_title.text isEqualToString:@"我的成长"]) {
            [self clickCell_mygrowup];
        }
        if ([label_title.text isEqualToString:@"意见反馈"]) {
            [self clickCell_opinion];
        }
        if ([label_title.text isEqualToString:@"系统设置"]) {
            [self clickCell_set];
        }
        if ([label_title.text isEqualToString:@"扫一扫"]) {
            [self clickCell_saoyisao];
        }

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row){
        case 0:{
            return 130;
        }break;
        default:{
            return 52;
        }break;
    }
}

#pragma mark - 通知体系 -
/**
 *  通知体系
 */
- (void)regist_notificationLeft{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification_list:) name:Notification_KWNFromFromList object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification_feedback:) name:Notification_KWNFromFeedback object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewWillAppear:) name:Notification_KWNIos6ReloadHome object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUnReadCount) name:@"updateUnReadCount" object:nil];
}

- (void)remove_notificationLeft{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:Notification_KWNFromFromList object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:Notification_KWNFromFeedback object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:Notification_KWNIos6ReloadHome object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"updateUnReadCount" object:nil];
}

- (void)receiveNotification_list:(NSNotification *)notification{
    //KWNQuestionListViewController *questionList = [[KWNQuestionListViewController alloc] init];
    [[RESideMenu sharedInstance] hideMenuViewController];
    //KWNHomeViewController *controller_home = (KWNHomeViewController *)[RESideMenu sharedInstance].contentViewController;
    //[controller_home pushViewController:questionList];
}

- (void)receiveNotification_feedback:(NSNotification *)notification{
    //KWNFeedbackViewController *feedback = [[KWNFeedbackViewController alloc] init];
    //[[RESideMenu sharedInstance] hideMenuViewController];
    //KWNHomeViewController *controller_home = (KWNHomeViewController *)[RESideMenu sharedInstance].contentViewController;
    //[controller_home pushViewController:feedback];
}

#pragma mark - 点击登录 -
/**
 *  点击登录
 */
- (void)didClickButton_login:(UIButton *)button{
    [[RESideMenu sharedInstance] hideMenuViewController];
    KWLLoginViewController *login = [[KWLLoginViewController alloc] initWithTag:4];
    [self pushViewController:login];
}

#pragma mark - 点击头像 -
/**
 *  点击头像
 */
-(void)didClickButton_portrait:(UIButton *)button{
    [[RESideMenu sharedInstance] hideMenuViewController];
    NSIndexPath *nowindex = [NSIndexPath indexPathForRow:0 inSection:0];

    if (![_index isEqual:nowindex])
    {
        if(_index){
            UITableViewCell *cell = [_tabel_list cellForRowAtIndexPath:_index];
            cell.backgroundColor = [UIColor clearColor];
            cell.contentView.backgroundColor = [UIColor clearColor];
        }
        _index = nowindex;
        if ([[RESideMenu sharedInstance].contentViewController isKindOfClass:[KWLScanCodeViewController class]])
        {
            //timer不放空  无法释放控制器
            KWLScanCodeViewController *control = (KWLScanCodeViewController *)[RESideMenu sharedInstance].contentViewController;
            [control.timer invalidate];
        }

        NSString *string_layer_id = _model_laywer.string_lawyerID;
        
        KWLLayerViewController *controller_layer = [[KWLLayerViewController alloc] initWithLaywerWithID:string_layer_id andState:1];
        if (IOS6_VERSION)
        {
            controller_layer.navigationController_MI = (MINavigationController *)[RESideMenu sharedInstance].navigationController;
        }
        [[RESideMenu sharedInstance] setContentViewController:controller_layer animated:YES];
    }
////    KWLHomeViewController *controller_home = (KWLHomeViewController *)[RESideMenu sharedInstance].contentViewController;
//    [(KWLHomeViewController *)[RESideMenu sharedInstance].contentViewController pushViewController:controller_layer];
}


@end
